/**
 * Created by shudong.msd(风骐) on 2016/4/17.
 */
'use strict';
app.controller('resultFilterBoxCtrl', ['$scope','dataFetcher','$compile','$state','$stateParams','$timeout',function($scope,dataFetcher,$compile,$state,$stateParams,$timeout) {

    $scope.myName = 'FilterBox';
    //注册scope
    dataFetcher.registScope($scope);

    dataFetcher.initData($stateParams.type);


    function isJson(obj) {
        return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    }

    function filterCheckedItem(dict){
        var res = [];
        for(var key in dict){
            if(dict[key]){
                res.push(key);
            }
        }
        return res;
    }

    //表单数据
    $scope.formData = {};

    // 处理表单{terminals:{t:true,a:true},...}
    $scope.processForm = function() {
        var tmpSubmitForm = angular.copy($scope.formData);
        for(var key in tmpSubmitForm){
            //if(formData[key] instanceof Object){
            if(isJson(tmpSubmitForm)){
                //$scope.formData[key] = converDictToList($scope.formData[key],$scope[key]);
                tmpSubmitForm[key] = filterCheckedItem(tmpSubmitForm[key]);
            }
        }

        dataFetcher.updateFiltersToData(tmpSubmitForm,$stateParams.type);
    };

    $scope.stateType = $stateParams.type;
    sessionStorage.setItem('stateType',$scope.stateType);

    $scope.resetData = function(){
        $state.reload('main.sResult.detail',{type:$scope.stateType});
    };

    $scope.buildMn = function(){
        var qt = dataFetcher.getQueryType();
        if(qt==0){
            $state.go('main.search.detail',{'type':'tv'},{reload:true});
        }else if(qt==1){
            $state.go('main.search.detail',{'type':'variety'},{reload:true});
        }else{
            $state.go('main.index.detail',{reload:true});
        }

    };

    $scope.toggleCheckbox = function(obj){
        obj.isCheckBoxShow = ! obj.isCheckBoxShow;
    };

    var getNameById = function(itemname,id){
        //if(itemname=='timeRange')return id;
        var tmpDictList = $scope[itemname].list;
        for(var i in tmpDictList){
            if(tmpDictList[i].id==id)return tmpDictList[i].name;
        }
        return '...';
    };

    $scope.submitItem = function(itemname){
        $scope[itemname].isCheckBoxShow = false;
        $scope[itemname].isItemShow = false;
        $scope[itemname].isItemSubmitted = true;
        var selectList = filterCheckedItem($scope.formData[itemname]);
        // 将选择的结果加入结果列表
        var targetEle = angular.element(".selectedItems-box .selectedItems");
        var tmpStr = "<li><a href='javascript:void(0)' ng-click=\"removeFromSelect($event,'"+itemname+"')\">"+$scope[itemname].itemType+"：";
        for(var i in selectList){
            tmpStr += getNameById(itemname,selectList[i])+", ";
        }
        tmpStr = tmpStr.substring(0,tmpStr.length-2);
        tmpStr += "</a></li>";
        var ele = $compile(tmpStr)($scope);//将click事件进行编译
        targetEle.append(ele);
        $scope.selectedCount+=1;

        changeCollapseItems('remove');
        $scope.changeCollapseShow();
    };

    $scope.selectedCount = 0;

    $scope.removeFromSelect = function(e,itemname){
        //显示列表，移除元素，清除表单，重新提交
        $scope[itemname].isItemShow = true;
        $scope[itemname].submitDisable = true;
        $scope[itemname].isItemSubmitted = false;
        var el = angular.element(e.target);
        el.parent().remove();
        $scope.formData[itemname] = {};
        $scope.selectedCount-=1;

        changeCollapseItems('add');
        $scope.changeCollapseShow();

        $scope.processForm();
    };

    $scope.updateSubmitStatus = function(itemname){
        /*
         1.冒泡很神奇啊，点击label，然后触发label的事件，此时的formData[itemname]为空，因为没有选中checkbox
         2.然后触发checkbox的click选中，formData[itemname]不为空
         3.然后事件冒泡再次出发label事件，相当于每点击一下触发2回label事件。
         */
        if($.isEmptyObject($scope.formData[itemname]))return;

        if(!$scope[itemname].isCheckBoxShow){
            $scope.submitItem(itemname);
            $scope.processForm();
            return;
        }
        var selectList = filterCheckedItem($scope.formData[itemname]);
        if(selectList.length>0){
            $scope[itemname].submitDisable = false;
        }else{
            $scope[itemname].submitDisable = true;
        }
    };

    $scope.updateDataByAlpha = function(e,itemname,alpha){
        e.stopPropagation();
        e.preventDefault();
        $scope[itemname].list = $scope[itemname].alphabetList[alpha];

        // 改变颜色
        var that = $(e.target);
        if(!that.hasClass("alphabet-selected")){
            that.addClass("alphabet-selected");
            $(".mz-res-filterbox .mz-filter-alpha-box .alphabet-list li a").not(that).removeClass("alphabet-selected")
        }
    };


    $scope.initDom = function(){
        //监听高度
        /*$(".mz-detect-title").on('resize',function(event){
            var h = $(this).css('height');
            if(h.substring(0, h.length-2)>219){
                $scope[event.target.getAttribute('data-dt')].heightEnough = true;
            }else{
                $scope[event.target.getAttribute('data-dt')].heightEnough = false;
            }
            if(!$scope.$$phase){
                $scope.$apply();
            }
        });*/

        $('.selectedItems-box').setScroll({
            parentContrainer:$('.mz-res-filterbox'),
            gap: 5,
            prevBoxs:[]
        });

    };


    $scope.collapseHidden = false;

    $scope.changeCollapseShow = function(){
        if($scope.collapseItems.length==0)$scope.collapseHidden = true;
        else $scope.collapseHidden = false;
    };

    $scope.isSpread = false;

    //$scope.collapseItems = ['languages','regions','stars','sex','ages','cities'];
    $scope.collapseItems = [];
    var notCollapseItems = [];

    $scope.listCollapse = function(){
        if(!$scope.isSpread){
            //展开
            for(var i in $scope.collapseItems){
                if(!$scope[$scope.collapseItems[i]].isItemSubmitted){
                    $scope[$scope.collapseItems[i]].isItemShow = true;
                }
            }
            $scope.isSpread = true;
        }else{
            //折叠
            for(var i in $scope.collapseItems){
                $scope[$scope.collapseItems[i]].isItemShow = false;
            }
            $scope.isSpread = false;
        }

    };

    var changeCollapseItems = function(method){
        if(method=='add'){//往collapseItems里加
            if(notCollapseItems.length==0)return;
            var name = notCollapseItems.pop();
            $scope.collapseItems.splice(0,0,name);
            if(!$scope.isSpread){
                $scope[name].isItemShow = false;
            }
        }else{
            if($scope.collapseItems.length==0)return;
            var name = $scope.collapseItems[0];
            $scope.collapseItems.splice(0,1);
            notCollapseItems.push(name);
            if(!$scope[name].isItemSubmitted){
                $scope[name].isItemShow = true;
            }

        }
    }

    $scope.toggleItemSpread = function(item){
        item.isItemSpread = !item.isItemSpread;
    };





    $scope.isCityModalShow = false;

    sessionStorage.setItem('whereIam','result');

    $scope.citySelectedData = {};

    $scope.addCityToScope = function(city){
        if($scope.citySelectedData[city.id]){
            $scope.cities.list.push(city);
        }else{
            for(var i in $scope.cities.list){
                if($scope.cities.list[i].id==city.id){
                    $scope.cities.list.splice(i,1);
                    break;
                }
            }
        }
    };

    $scope.selectInfo = {
        'cities':false
    };

    $scope.citiesDynamicDom = new dynamicDom({
        source: null,
        target: null,
        resultTitle : null,
        targetItemClass : "list-group-item list-category_item selected-city",
        removeButton : null
    });

    var cityInit = false;

    $scope.initAction=function() {

        if(cityInit)return;
        cityInit = true;
        //模态框 字母列表
        $(".mz-res-filterbox .mz-res-modal .alphabet-list li a").unbind('click');
        $(".mz-res-filterbox .mz-res-modal .alphabet-list li a").click(function(){
            if(!$(this).hasClass("alphabet-selected")){
                $(this).addClass("alphabet-selected");
                $(".mz-res-filterbox .mz-res-modal .alphabet-list li a").not(this).removeClass("alphabet-selected")
            }
        });
        //************************城市model部分
        $scope.citiesDynamicDom.setTarget($(".mz-res-filterbox .mz-res-modal .selected-cities"));
        $scope.citiesDynamicDom.setResultTitle($(".mz-res-filterbox .mz-res-modal .city-result-title span"));
        $scope.citiesDynamicDom.setRemoveButton($(".mz-res-filterbox .mz-res-modal .remove-all-cities"));


        var comutil = new commUtils();

        //城市选择搜索框
        //var cites = ['北京','上海','杭州','北海','北极'];

        var citesBlood = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.whitespace('name'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            //local: cites,
            //prefetch: '本地数据.json',//速度快
            remote: {
                url: UrlMappings.REGION_KEYWORD_SEARCH+'?q=%QUERY&access_token='+comutil.getTocken(),
                wildcard:'%QUERY'
            }
        });
        var cityTypeahead = $('.mz-res-filterbox .mz-res-modal .search-region-group .typeahead').typeahead({
                hint: true,
                highlight: true,
                minLength: 1
            },
            {
                name: 'cities-data',
                display : 'name',
                source: citesBlood,
                limit: 5
            }
        );
        //绑定选择后以及焦点改变时发生的事件
        cityTypeahead.bind('typeahead:select', function(ev, suggestion) {
            //选择该城市
            $scope.citiesDynamicDom.addToTarget(suggestion.name);
        });

        $('.mz-res-filterbox .mz-res-modal .choose-city-footer button:first-of-type').off('click');
        $('.mz-res-filterbox .mz-res-modal .choose-city-footer button:first-of-type').on('click', function () {
            $scope.citiesDynamicDom.removeAllSelect();
        });

        $scope.selectAllCity = function(){
            if($scope.selectInfo['cities']){
                $scope.selectInfo['cities'] = false;
                $timeout(function() {
                    for (var i in $scope['hotCities']) {
                        //$scope.formData['cities'][$scope['hotCities'][i]]=false;
                        if ($scope.citySelectedData[$scope['hotCities'][i].id]) {
                            $scope.citiesDynamicDom.removeTargetDir($scope['hotCities'][i].name);
                        }
                    }
                });
            }else{
                $scope.selectInfo['cities'] = true;
                $timeout(function(){
                    for(var i in $scope['hotCities']){
                        if(!$scope.citySelectedData[$scope['hotCities'][i].id]){
                            $scope.citiesDynamicDom.addToTarget($scope['hotCities'][i].name);
                        }
                    }
                });

            }
        };

        $scope.checkSelectAllCity = function(city){
            var count = 0;
            for(var key in $scope.citySelectedData){
                if($scope.citySelectedData[key]){
                    for(var j in $scope['hotCities']){
                        if($scope['hotCities'][j].id==key){
                            count++;
                            break;
                        }
                    }
                }
            }
            if(count==$scope['hotCities'].length){
                $scope.selectInfo['cities'] = true;
            }else{
                $scope.selectInfo['cities'] = false;
            }

            $scope.addCityToScope(city);
        }

    };

    $scope.citySubmit = function(){
        /*
            //包括总体
            for(var i in $scope.cities.list){
            $scope.formData['cities'][$scope.cities.list[i]] = true;
        }*/

        //不包括总体
        $scope.formData['cities'] = angular.copy($scope.citySelectedData);

        $scope.submitItem("cities");

        $scope.processForm();
    }

}]);
